import { post } from '../../services/request.js'

const state = {
  currentLocation: null,
  locationStatus: {
    enabled: false,
    status: 'pending', // 'pending' | 'locating' | 'success' | 'error'
    text: '位置获取中...',
    accuracy: 'high',
    lastUpdate: null,
    error: null
  },
  locationHistory: [],
  // WebSocket 连接状态
  wsConnected: false,
  // 实时推送设置
  realTimePushEnabled: true,
  // 定时上报相关
  autoUploadTimer: null,
  autoUploadEnabled: true,
  uploadInterval: 2 * 60 * 1000 // 2分钟上报一次
}

const mutations = {
  SET_CURRENT_LOCATION(state, location) {
    state.currentLocation = location
    state.locationStatus.lastUpdate = new Date().toISOString()
  },
  SET_LOCATION_STATUS(state, status) {
    state.locationStatus = { ...state.locationStatus, ...status }
  },
  ADD_LOCATION_HISTORY(state, location) {
    state.locationHistory.unshift({
      ...location,
      timestamp: new Date().toISOString()
    })
    // 只保留最近100条记录
    if (state.locationHistory.length > 100) {
      state.locationHistory = state.locationHistory.slice(0, 100)
    }
  },
  // WebSocket 相关状态
  SET_WS_CONNECTED(state, connected) {
    state.wsConnected = connected
  },
  SET_REAL_TIME_PUSH_ENABLED(state, enabled) {
    state.realTimePushEnabled = enabled
  },
  // 定时器相关状态
  SET_AUTO_UPLOAD_TIMER(state, timer) {
    state.autoUploadTimer = timer
  },
  SET_AUTO_UPLOAD_ENABLED(state, enabled) {
    state.autoUploadEnabled = enabled
  },
  SET_UPLOAD_INTERVAL(state, interval) {
    state.uploadInterval = interval
  }
}

const actions = {
  // 检查位置权限
  async checkLocationPermission() {
    return new Promise((resolve) => {
      uni.getSetting({
        success: (res) => {
          const hasPermission = res.authSetting['scope.userLocation']
          resolve(hasPermission)
        },
        fail: () => {
          resolve(false)
        }
      })
    })
  },

  // 请求位置权限
  async requestLocationPermission() {
    return new Promise((resolve) => {
      uni.authorize({
        scope: 'scope.userLocation',
        success: () => {
          resolve(true)
        },
        fail: () => {
          resolve(false)
        }
      })
    })
  },

  // 获取当前位置（带权限处理）
  async getCurrentLocation({ commit, dispatch }) {
    return new Promise(async (resolve, reject) => {
      try {
        // 先检查权限
        let hasPermission = await dispatch('checkLocationPermission')
        
        // 如果权限未确定，尝试请求权限
        if (hasPermission === undefined) {
          hasPermission = await dispatch('requestLocationPermission')
        }
        
        // 如果没有权限，提供默认位置
        if (hasPermission === false) {
          console.warn('位置权限被拒绝，使用默认位置')
          const defaultLocation = {
            latitude: 39.9042,
            longitude: 116.4074,
            accuracy: 0,
            address: '北京市朝阳区建国门外大街1号（默认位置）',
            isDefault: true
          }
          
          commit('SET_CURRENT_LOCATION', defaultLocation)
          commit('SET_LOCATION_STATUS', {
            enabled: false,
            status: 'error',
            text: '位置权限未授权',
            error: '位置权限未授权，使用默认位置'
          })
          resolve(defaultLocation)
          return
        }

        // 获取实际位置
        uni.getLocation({
          type: 'gcj02',
          success: (res) => {
            const location = {
              latitude: res.latitude,
              longitude: res.longitude,
              accuracy: res.accuracy,
              address: '当前位置',
              isDefault: false
            }
            
            commit('SET_CURRENT_LOCATION', location)
            commit('ADD_LOCATION_HISTORY', location)
            commit('SET_LOCATION_STATUS', {
              enabled: true,
              status: 'success',
              text: '定位成功',
              error: null
            })
            resolve(location)
          },
          fail: (error) => {
            console.error('获取位置失败:', error)
            // 位置获取失败时也提供默认位置
            const defaultLocation = {
              latitude: 39.9042,
              longitude: 116.4074,
              accuracy: 0,
              address: '北京市朝阳区建国门外大街1号（默认位置）',
              isDefault: true
            }
            
            commit('SET_CURRENT_LOCATION', defaultLocation)
            commit('SET_LOCATION_STATUS', {
              enabled: false,
              status: 'error',
              text: '定位失败',
              error: `位置获取失败: ${error.errMsg || error.message}`
            })
            resolve(defaultLocation) // 改为 resolve 而不是 reject，避免中断其他数据加载
          }
        })
      } catch (error) {
        console.error('位置权限检查失败:', error)
        // 异常情况也提供默认位置
        const defaultLocation = {
          latitude: 39.9042,
          longitude: 116.4074,
          accuracy: 0,
          address: '北京市朝阳区建国门外大街1号（默认位置）',
          isDefault: true
        }
        
        commit('SET_CURRENT_LOCATION', defaultLocation)
        commit('SET_LOCATION_STATUS', {
          enabled: false,
          status: 'error',
          text: '位置服务异常',
          error: '位置服务异常，使用默认位置'
        })
        resolve(defaultLocation)
      }
    })
  },

  // 更新位置状态
  async updateLocationStatus({ commit, dispatch }) {
    try {
      // 获取位置（已包含权限处理和容错）
      const location = await dispatch('getCurrentLocation')
      commit('SET_LOCATION_STATUS', {
        enabled: !location.isDefault,
        status: location.isDefault ? 'error' : 'success',
        text: location.isDefault ? '使用默认位置' : '定位成功',
        lastUpdate: new Date().toISOString(),
        error: location.isDefault ? '使用默认位置' : null
      })
      return location
    } catch (error) {
      // 这种情况很少见，因为getCurrentLocation已经做了容错
      console.error('位置状态更新异常:', error)
      commit('SET_LOCATION_STATUS', {
        enabled: false,
        status: 'error',
        text: '位置服务异常',
        error: error.message || '位置服务异常'
      })
      return {
        latitude: 39.9042,
        longitude: 116.4074,
        accuracy: 0,
        address: '默认位置',
        isDefault: true
      }
    }
  },

  // 开始位置监听
  startLocationWatch({ commit }) {
    const watchId = uni.onLocationChange((res) => {
      const location = {
        latitude: res.latitude,
        longitude: res.longitude,
        accuracy: res.accuracy,
        address: '实时位置更新'
      }
      
      commit('SET_CURRENT_LOCATION', location)
      commit('ADD_LOCATION_HISTORY', location)
    })
    
    return watchId
  },

  // 停止位置监听
  stopLocationWatch() {
    uni.offLocationChange()
  },

  // 上传位置信息到服务器
  async uploadLocation({ state, commit }, payload = {}) {
    try {
      const currentLocation = state.currentLocation
      if (!currentLocation) {
        console.warn('没有位置信息可上传')
        return { success: false, message: '没有位置信息' }
      }

      // 如果是默认兜底位置（定位失败/未授权），跳过上传，避免污染大屏
      if (currentLocation.isDefault) {
        console.warn('定位失败或未授权，跳过上传默认坐标')
        commit('SET_LOCATION_STATUS', {
          ...state.locationStatus,
          status: 'error',
          text: '定位未授权/失败，未上传',
          error: '默认位置，跳过上传'
        })
        return { success: false, message: '默认位置，未上传' }
      }

      // 构建上传数据 - 对应后端接口格式
      const locationData = {
        latitude: currentLocation.latitude,
        longitude: currentLocation.longitude,
        accuracy: currentLocation.accuracy || 10,
        address: currentLocation.address,
        floor: payload.floor,
        department: payload.department,
        timestamp: Date.now(),
        deviceType: 'wxapp',
        isDefault: !!currentLocation.isDefault,
        ...payload
      }

      console.log('上传位置信息到后端:', locationData)
      
      // 调用后端位置上报API
      const response = await post('/v1/location/upload', locationData)
      
      if (response.success) {
        // 更新状态
        commit('SET_LOCATION_STATUS', {
          ...state.locationStatus,
          status: 'success',
          text: '位置上传成功',
          lastUpdate: new Date().toISOString()
        })
        
        return {
          success: true,
          data: response.data,
          message: '位置信息上传成功'
        }
      } else {
        throw new Error(response.message || '上传失败')
      }
    } catch (error) {
      console.error('上传位置信息失败:', error)
      
      // 更新错误状态
      commit('SET_LOCATION_STATUS', {
        ...state.locationStatus,
        status: 'error',
        text: '位置上传失败',
        error: error.message
      })
      
      return {
        success: false,
        error: error.message || '上传失败',
        message: '位置信息上传失败'
      }
    }
  },

  // WebSocket 实时推送相关
  async initRealtimePush({ commit, state, rootGetters }) {
    try {
      // 获取 WebSocket 管理器
      const wsManager = (await import('../../utils/websocket.js')).default
      
      // 获取用户token
      const token = rootGetters['auth/token']
      if (!token) {
        console.warn('没有用户token，无法建立WebSocket连接')
        return
      }

      // 检查 wsManager 是否正确导入
      if (!wsManager || typeof wsManager.on !== 'function') {
        console.warn('WebSocket管理器导入失败，暂时跳过实时推送')
        commit('SET_WS_CONNECTED', false)
        return
      }

      // 监听WebSocket事件
      wsManager.on('open', () => {
        console.log('位置服务WebSocket连接成功')
        commit('SET_WS_CONNECTED', true)
        
        // 订阅位置频道
        wsManager.send({
          type: 'subscribe',
          channel: 'location',
          data: {
            userId: rootGetters['auth/userInfo']?.id
          }
        })
      })

      wsManager.on('close', () => {
        console.log('位置服务WebSocket连接关闭')
        commit('SET_WS_CONNECTED', false)
      })

      // 监听位置相关消息
      wsManager.on('location.update', (data) => {
        console.log('收到位置更新:', data)
        // 这里可以处理其他用户的位置更新
      })

      wsManager.on('location.request', (data) => {
        console.log('收到位置请求:', data)
        // 处理紧急情况位置请求
        uni.showModal({
          title: '位置请求',
          content: `收到${data.type}请求，是否共享当前位置？`,
          confirmText: '同意',
          cancelText: '拒绝',
          success: (res) => {
            if (res.confirm && state.currentLocation) {
              // 发送当前位置
              wsManager.send({
                type: 'location.response',
                requestId: data.requestId,
                location: state.currentLocation
              })
            }
          }
        })
      })

      // 建立连接
      wsManager.connect(token)

    } catch (error) {
      console.error('初始化位置实时推送失败:', error)
    }
  },

  // 实时推送位置数据
  async pushLocationUpdate({ state, commit }) {
    try {
      if (!state.wsConnected || !state.realTimePushEnabled) {
        return
      }

      const wsManager = (await import('../../utils/websocket.js')).default
      
      // 检查wsManager是否可用
      if (!wsManager || typeof wsManager.send !== 'function') {
        console.warn('WebSocket管理器不可用，跳过实时推送')
        return
      }
      
      if (state.currentLocation && !state.currentLocation.isDefault) {
        // 通过WebSocket实时推送位置更新
        wsManager.send({
          type: 'location.broadcast',
          data: {
            ...state.currentLocation,
            timestamp: Date.now()
          }
        })
        
        console.log('位置数据已实时推送')
      }
    } catch (error) {
      console.error('实时推送位置失败:', error)
    }
  },

  // 切换实时推送
  toggleRealTimePush({ commit, dispatch }, enabled) {
    commit('SET_REAL_TIME_PUSH_ENABLED', enabled)
    
    // 保存设置到本地
    try {
      uni.setStorageSync('location_realtime_push', enabled)
    } catch (e) {
      console.warn('保存实时推送设置失败:', e)
    }

    // 如果开启实时推送且有当前位置，立即推送
    if (enabled) {
      dispatch('pushLocationUpdate')
    }
  },

  // 启动定时位置上报
  startAutoUpload({ commit, dispatch, state, rootGetters }) {
    // 如果已经有定时器在运行，先清除
    if (state.autoUploadTimer) {
      clearInterval(state.autoUploadTimer)
    }

    // 检查是否启用自动上报
    if (!state.autoUploadEnabled) {
      console.log('自动位置上报已禁用')
      return
    }

    console.log(`开始定时位置上报，间隔: ${state.uploadInterval / 1000}秒`)
    
    const timer = setInterval(async () => {
      try {
        // 检查登录状态
        const isLoggedIn = rootGetters['auth/isLoggedIn']
        const token = rootGetters['auth/token']
        
        if (!isLoggedIn || !token) {
          console.log('用户未登录，跳过定时位置上报')
          return
        }

        // 获取最新位置并上报
        const location = await dispatch('getCurrentLocation')
        if (location && !location.isDefault) {
          await dispatch('uploadLocation', {
            deviceType: 'wxapp',
            source: 'auto_timer'
          })
          console.log(`✅ 定时位置上报成功: ${new Date().toLocaleTimeString()}`)
        } else {
          console.log('定时位置上报：位置无效或为默认位置，跳过上报')
        }
      } catch (error) {
        console.error('定时位置上报失败:', error)
      }
    }, state.uploadInterval)

    commit('SET_AUTO_UPLOAD_TIMER', timer)
    console.log('定时位置上报已启动')
  },

  // 停止定时位置上报
  stopAutoUpload({ commit, state }) {
    if (state.autoUploadTimer) {
      clearInterval(state.autoUploadTimer)
      commit('SET_AUTO_UPLOAD_TIMER', null)
      console.log('定时位置上报已停止')
    }
  },

  // 重启定时上报（更改间隔时使用）
  restartAutoUpload({ dispatch }) {
    dispatch('stopAutoUpload')
    dispatch('startAutoUpload')
  },

  // 设置上报间隔
  setUploadInterval({ commit, dispatch }, interval) {
    commit('SET_UPLOAD_INTERVAL', interval)
    dispatch('restartAutoUpload')
  },

  // 启用/禁用自动上报
  toggleAutoUpload({ commit, dispatch, state }, enabled) {
    commit('SET_AUTO_UPLOAD_ENABLED', enabled)
    
    if (enabled) {
      dispatch('startAutoUpload')
    } else {
      dispatch('stopAutoUpload')
    }
  }
}

const getters = {
  currentLocation: state => state.currentLocation,
  locationStatus: state => state.locationStatus,
  locationHistory: state => state.locationHistory,
  isLocationEnabled: state => state.locationStatus.enabled,
  // WebSocket 相关状态
  isWSConnected: state => state.wsConnected,
  isRealTimePushEnabled: state => state.realTimePushEnabled,
  // 定时上报相关状态
  isAutoUploadEnabled: state => state.autoUploadEnabled,
  uploadInterval: state => state.uploadInterval,
  isAutoUploadRunning: state => !!state.autoUploadTimer
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}